#include <stdio.h>
#include <fcntl.h>
#include <gtk/gtk.h>
#include <glib.h>

FILE *fd;
FILE *configFD;
int fanOnVal = 0;
int fanOffVal = 0;
int fanIntervalVal = 0;

extern GtkWidget *fanOnAdjustment;
extern GtkWidget *fanOffAdjustment;
extern GtkWidget *intervalAdjustment;

void openDevice(void)
{
	fd = fopen("/dev/port", "r+");
	if(!fd)
	{
		printf("error opening /dev/port for communication\n");
	}
}

void closeDevice(void)
{
	fclose(fd);
	printf("io to device is closed\n");
}

void writeConfig(void)
{
	int tmp = 99;

	configFD = fopen("/etc/acerfand.conf", "w");
	if(!configFD)
	{
		printf("config file did not open [0x%08x]\n", configFD);
		return;
	}
	fprintf(configFD, "#fileGen=0\n");
	fprintf(configFD, "INTERVAL=%d\n", fanIntervalVal);
	fprintf(configFD, "FAN_ON=%d\n", fanOnVal);
	fprintf(configFD, "FANOFF=%d\n", fanOffVal);
	
	printf("INTERVAL=%d\n", fanIntervalVal);
	printf("FAN_ON=%d\n", fanOnVal);
	printf("FANOFF=%d\n", fanOffVal);
	fclose(configFD);
}

void openConfig(void)
{
	char variable[32];
	char value[32];
	int i;

	configFD = fopen("/etc/acerfand.conf", "r+");
	if(!configFD)
	{
		printf("config file did not open [0x%08x]\n", configFD);
		return;
	}
	while(!feof(configFD))
	{
		fscanf(configFD, "%[^=]%s\n", variable, value);
		if(variable[0] == "\0" || value[0] == "\0")
			break;
		for(i=0;i<31;i++)
		{
			value[i] = value[i+1];
		}
		value[31]="\0";
		printf("var [%s] is set to [%s] -- [%d]\n", variable, value, atoi(value));
		if(strcmp(variable, "INTERVAL") == 0)
			fanIntervalVal = atoi(value);
		else if(strcmp(variable, "FANOFF") == 0)
			fanOffVal = atoi(value);
		else if(strcmp(variable, "FAN_ON") == 0)
			fanOnVal = atoi(value);
		else
			printf("variable [%s] notrecognized\n", variable);
	}
	printf("Completed dump of configuration file\n");
	printf("intervalVal [%d]\tfanOnVal [%d]\tfanOffVal [%d]\n", fanIntervalVal, fanOnVal, fanOffVal);
	fclose(configFD);
}

void closeConfig(void)
{
	fclose(configFD);
}
	
